package com.pocketsweet.ui.uilib.adapter;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVCloud;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FunctionCallback;
import com.avos.avoscloud.GetCallback;
import com.avos.avoscloud.SaveCallback;
import com.pocketsweet.C;
import com.pocketsweet.R;
import com.pocketsweet.model.MLOrder;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.Appraise;
import com.pocketsweet.ui.Profile;
import com.pocketsweet.ui.uilib.MyAlertDialog;
import com.pocketsweet.ui.uilib.MyRatingBar;
import com.pocketsweet.utils.ToolKits;

/**
 * 
 * @author Kam
 * 
 */
public class AppraiseAdapter extends BaseListAdapter<MLOrder> {
	public AppraiseAdapter(Context ctx) {
		super(ctx);
	}

	public AppraiseAdapter(Context ctx, List<MLOrder> datas) {
		super(ctx, datas);
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder viewHolder = null;
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.item_appraise, parent,
					false);
			viewHolder = new ViewHolder(convertView);
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		viewHolder.refreshView(datas.get(position), position);
		return convertView;
	}

	public class ViewHolder implements View.OnClickListener {
		ImageView imgAvatar;
		TextView tvuserName;
		TextView tvOrderTime;
		TextView tvOrderFinishTime;
		TextView tvGoToComment;
		TextView tvAppraise;
		TextView tvDefault;
		LinearLayout grade;
		RatingBar rating_bar;
		int score = 0;
		MLUser mlUser;
		MLOrder mlOrder;
		private View parent;

		Handler myHandler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 0:
					rating_bar.setRating(score);
					// rating_bar.setNumStars(score);
					tvGoToComment.setVisibility(View.GONE);
					rating_bar.setVisibility(View.VISIBLE);
					tvDefault.setVisibility(View.GONE);
					break;
				}
				super.handleMessage(msg);
			}
		};

		private ViewHolder(View parent) {
			this.parent = parent;
			initView(parent);
		}

		public void initView(View parent) {
			imgAvatar = (ImageView) parent.findViewById(R.id.imgAvatar);
			tvuserName = (TextView) parent.findViewById(R.id.tvuserName);
			tvOrderTime = (TextView) parent.findViewById(R.id.tvOrderTime);
			tvDefault = (TextView) parent.findViewById(R.id.tvDefault);
			tvGoToComment = (TextView) parent.findViewById(R.id.tvGoToComment);
			tvOrderFinishTime = (TextView) parent
					.findViewById(R.id.tvOrderFinishTime);
			tvAppraise = (TextView) parent.findViewById(R.id.tvAppraise);
			grade = (LinearLayout) parent.findViewById(R.id.grade);
			rating_bar = (RatingBar) parent.findViewById(R.id.rating_appraise);
		}

		public void refreshView(MLOrder mlOrder, int i) {
			this.mlOrder = mlOrder;
			mlUser = mlOrder.getWinner();
			String avatar = mlUser.getAvatarUrl();
			if (avatar != null && !avatar.equals("")) {
				UserService.displaySquare(avatar, imgAvatar);
			} else {
				imgAvatar.setImageResource(R.drawable.default_user_avatar);
			}
			if (mlOrder.getCommentStatus() != 0) {
				if (mlOrder.getCommentStatus() < 6) {
					rating_bar.setRating(mlOrder.getCommentStatus());
					// rating_bar.setMax(mlOrder.getCommentStatus());
					// rating_bar.setNumStars(mlOrder.getCommentStatus());
					tvGoToComment.setVisibility(View.GONE);
					rating_bar.setVisibility(View.VISIBLE);
					tvDefault.setVisibility(View.GONE);
				} else if (mlOrder.getCommentStatus() == 6) {// 默认好评
					rating_bar.setRating(5);
					// rating_bar.setMax(mlOrder.getCommentStatus());
					// rating_bar.setNumStars(5);
					tvGoToComment.setVisibility(View.GONE);
					rating_bar.setVisibility(View.VISIBLE);
					tvDefault.setVisibility(View.VISIBLE);

				}
			} else {
				rating_bar.setVisibility(View.GONE);
				tvGoToComment.setVisibility(View.VISIBLE);
				tvDefault.setVisibility(View.GONE);
			}
			// 设置姓名
			tvOrderTime.setText(ToolKits.translateMinToStandard((long) mlOrder
					.getPeriod()) + "订单");// 几分钟订单
			tvOrderFinishTime.setText(ToolKits.getTimeDiff(mlOrder
					.getUpdatedAt()));// 几分钟之前
			tvuserName.setText(mlUser.getNickname());
			tvGoToComment.setOnClickListener(this);
			parent.setOnClickListener(this);
		}

		@Override
		public void onClick(View v) {
			if (v.equals(tvGoToComment)) {
				AVAnalytics.onEvent(ctx, "点击评价按钮");
				final MyRatingBar ratingBar = new MyRatingBar(ctx);
				MyAlertDialog dialog = new MyAlertDialog(ctx).builder()
						.setTitle("给Ta评个分").setView(ratingBar)
						.setNegativeButton("取消", new OnClickListener() {
							@Override
							public void onClick(View v) {
							}
						});
				dialog.setPositiveButton("确定", new OnClickListener() {
					@Override
					public void onClick(View v) {
						score = ratingBar.getScore();
						if (score <= 0) {
							return;
						}
						AVQuery<MLOrder> query = new AVQuery<MLOrder>("MLOrder");
						query.getInBackground(mlOrder.getObjectId().toString(),
								new GetCallback<MLOrder>() {

									@Override
									public void done(MLOrder thisOrder,
											AVException arg1) {
										// TODO Auto-generated method stub
										if (arg1 == null) {
											if (thisOrder != null) {
												if (thisOrder.getStatus() == C.ORDER_STATUS_COMMENT) {// 未评价
													MLOrder order = new MLOrder();
													order.setObjectId(mlOrder
															.getObjectId());
													order.setCommentStatus(score);
													order.setStatus(C.ORDER_STATUS_FINISH);
													order.saveInBackground(new SaveCallback() {

														@Override
														public void done(
																AVException arg0) {
															// TODO
															// Auto-generated
															// method stub
															if (arg0 == null) {
																double price = 0;
																if (score <= 3) {
																	price = 0;
																} else if (score == 4) {
																	price = mlOrder
																			.getCost() / 10 * 0.8;
																} else if (score == 5) {
																	price = mlOrder
																			.getCost() / 10;
																}
																BigDecimal balanceFormat = new BigDecimal(
																		price)
																		.setScale(
																				2,
																				BigDecimal.ROUND_HALF_UP);
																price = balanceFormat
																		.doubleValue();
																// 调用云代码给恋爱体验师钱
																Map<String, Object> params = new HashMap<String, Object>();
																params.put(
																		"price",
																		price);
																params.put(
																		"userId",
																		mlOrder.getWinner()
																				.getObjectId());
																AVCloud.callFunctionInBackground(
																		"BalanceAccount",
																		params,
																		new FunctionCallback<Object>() {

																			@Override
																			public void done(
																					Object arg0,
																					AVException e) {
																				// TODO
																				// Auto-generated
																				// method
																				// stub
																				if (e == null) {
																					Message message = new Message();
																					message.what = 0;
																					myHandler
																							.sendMessage(message);
																				}

																			}
																		});

															}
														}
													});
												} else {
													ToolKits.toast(ctx,
															"该评价已超时，已自动设置为默认好评");
												}
											}
										}
									}
								});

					}
				});
				dialog.show();
			} else if (v.equals(parent)) {
				String selectedUserId = mlOrder.getWinner().getObjectId();
				Intent intent = new Intent(ctx, Profile.class);
				intent.putExtra("userId", selectedUserId);
				intent.putExtra("nickname", mlOrder.getWinner().getNickname());
				ctx.startActivity(intent);
			}
		}
	}
}
